package jp.dev7.manofac;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * @author manofac
 */
public class CommonsFileUploadServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private static final String TMP_DIR_PATH = "photo";
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH = "photo";
    private File destinationDir;

    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        tmpDir = new File(getServletContext().getRealPath(TMP_DIR_PATH));
        if (!tmpDir.isDirectory()) {
            throw new ServletException(TMP_DIR_PATH + " is not a directory");
        }

        destinationDir = new File(getServletContext().getRealPath(DESTINATION_DIR_PATH));
        if (!destinationDir.isDirectory()) {
            throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        // response.setContentType("text/plain");
        // out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
        response.setContentType("text/javascript");
        response.setCharacterEncoding("utf-8");

        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        /*
         * Set the size threshold, above which content will be stored on disk.
         */
        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
        /*
         * Set the temporary directory to store the uploaded files of size above threshold.
         */
        fileItemFactory.setRepository(tmpDir);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

        try {
            /*
             * Parse the request
             */
            @SuppressWarnings("unchecked")
            List<FileItem> items = uploadHandler.parseRequest(request);

            for (FileItem fileItem : items) {
                if (fileItem.isFormField()) {
                    // フィールドのサンプル。実装なし
                    if (fileItem.getFieldName().equalsIgnoreCase("email")) {
                        String emailIdString = fileItem.getString();
                        log("e-mail:" + emailIdString.toString());
                    }
                } else {
                    File file = new File(destinationDir, fileItem.getName());

                    fileItem.write(file);

                    log("ファイルを出力：" + file.getAbsolutePath());

                    // TODO サムネイル画像をJSONで返す。
                    // TODO path指定おかしい
                    // IE6でevalしたら死ぬ
                    // out.println("{'photo_url' : '" + "../" + DESTINATION_DIR_PATH + "/" + fileItem.getName() + "' ,}");
                    out.println("{'photo_url' : '" + "../" + DESTINATION_DIR_PATH + "/" + fileItem.getName() + "'}");
                }
            }

        } catch (FileUploadException ex) {
            log("Error encountered while parsing the request", ex);
        } catch (Exception ex) {
            log("Error encountered while uploading file", ex);
        }
    }
}
